package com.cxliu.cnews.Weather.Api;

import com.cxliu.cnews.R;
import com.cxliu.cnews.Weather.Bean.LocationBean;
import com.cxliu.cnews.Weather.Bean.WeatherBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * Created by lcx on 2016/7/11.
 */

public class ApiManager {
    public static ApiService apiManager;

    public static ApiService getApi() {
        if (apiManager == null) {
            intAPI();
        }
        return apiManager;
    }

    public static void intAPI() {
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl("http://api.map.baidu.com/geocoder/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
        apiManager = mRetrofit.create(ApiService.class);
    }

    public interface ApiService {
        @Headers("User-Agent:Mozilla/5.0")
        @GET("http://api.map.baidu.com/geocoder?output=json&referer=32D45CBEEC107315C553AD1131915D366EEF79B4&location={longtitude},{latitude}")
        Observable<LocationBean> getLocationInfo(@Path("longtitude") String longtitude, @Path("latitude") String latitude);

        @Headers("User-Agent:Mozilla/5.0")
        @GET("http://wthrcdn.etouch.cn/weather_mini?city=南京")
        Observable<ResponseBody> getWeatherInfo();//(@Query("city") String city);
    }

    /**
     * 获取城市信息列表接口
     *
     * @param callback
     */
    public static void getLocationInfo(String longtitude, String latitude, final LocationApiInterface callback) {
        getApi().getLocationInfo(longtitude, latitude).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).unsubscribeOn(Schedulers.io())
                .subscribe(new Action1<LocationBean>() {
                               @Override
                               public void call(LocationBean locationBean) {
                                   if (locationBean == null) {
                                       callback.onFail();
                                   } else {
                                       callback.onSuccess(locationBean);
                                   }
                               }
                           }
                        , new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                callback.onFail();
                            }
                        });
    }


    public static void getWeatherInfo(String city, final WeatherApiInterface callback) {
        //URLEncoder.encode(city, "utf-8")
//        try {
            getApi().getWeatherInfo().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).unsubscribeOn(Schedulers.io())
                    .subscribe(new Action1<ResponseBody>() {
                                   @Override
                                   public void call(ResponseBody responseBody) {
                                       if (responseBody == null) {
                                           callback.onFail();
                                       } else {
                                           String jsonString = null;
                                           try {
                                               jsonString = responseBody.string();
                                           } catch (IOException e) {
                                               e.printStackTrace();
                                               callback.onFail();
                                           }
                                           try {
                                               JSONObject obj = new JSONObject(jsonString);
                                               JSONObject dataJsonObj = obj.getJSONObject("data");
                                               JSONArray weatherJsonArray = dataJsonObj.getJSONArray("forecast");
                                               List<WeatherBean> list = new ArrayList<WeatherBean>();
                                               for (int i = 0; i < weatherJsonArray.length(); i++) {
                                                   WeatherBean weatherBean = getWeatherBeanFromJson(weatherJsonArray.getJSONObject(i));
                                                   list.add(weatherBean);
                                               }
                                               callback.onSuccess(list);
                                           } catch (JSONException e) {
                                               callback.onFail();
                                               e.printStackTrace();
                                           }
                                       }
                                   }
                               }
                            , new Action1<Throwable>() {
                                @Override
                                public void call(Throwable throwable) {
                                    callback.onFail();
                                }
                            });
//        }
//        catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
    }


    private static WeatherBean getWeatherBeanFromJson(JSONObject jsonObject) {
        WeatherBean weatherBean = new WeatherBean();
        try {
            String temperature = jsonObject.get("high").toString() + " " + jsonObject.get("low").toString();
            String weather = jsonObject.get("type").toString();
            String wind = jsonObject.get("fengxiang").toString();
            String date = jsonObject.get("date").toString();
            weatherBean.setDate(date);
            weatherBean.setTemperature(temperature);
            weatherBean.setWeather(weather);
            weatherBean.setWeek(date.substring(date.length() - 3));
            weatherBean.setWind(wind);
            weatherBean.setImageRes(getWeatherImage(weather));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return weatherBean;
    }

    public static int getWeatherImage(String weather) {
        if (weather.equals("多云") || weather.equals("多云转阴") || weather.equals("多云转晴")) {
            return R.drawable.biz_plugin_weather_duoyun;
        } else if (weather.equals("中雨") || weather.equals("中到大雨")) {
            return R.drawable.biz_plugin_weather_zhongyu;
        } else if (weather.equals("雷阵雨")) {
            return R.drawable.biz_plugin_weather_leizhenyu;
        } else if (weather.equals("阵雨") || weather.equals("阵雨转多云")) {
            return R.drawable.biz_plugin_weather_zhenyu;
        } else if (weather.equals("暴雪")) {
            return R.drawable.biz_plugin_weather_baoxue;
        } else if (weather.equals("暴雨")) {
            return R.drawable.biz_plugin_weather_baoyu;
        } else if (weather.equals("大暴雨")) {
            return R.drawable.biz_plugin_weather_dabaoyu;
        } else if (weather.equals("大雪")) {
            return R.drawable.biz_plugin_weather_daxue;
        } else if (weather.equals("大雨") || weather.equals("大雨转中雨")) {
            return R.drawable.biz_plugin_weather_dayu;
        } else if (weather.equals("雷阵雨冰雹")) {
            return R.drawable.biz_plugin_weather_leizhenyubingbao;
        } else if (weather.equals("晴")) {
            return R.drawable.biz_plugin_weather_qing;
        } else if (weather.equals("沙尘暴")) {
            return R.drawable.biz_plugin_weather_shachenbao;
        } else if (weather.equals("特大暴雨")) {
            return R.drawable.biz_plugin_weather_tedabaoyu;
        } else if (weather.equals("雾") || weather.equals("雾霾")) {
            return R.drawable.biz_plugin_weather_wu;
        } else if (weather.equals("小雪")) {
            return R.drawable.biz_plugin_weather_xiaoxue;
        } else if (weather.equals("小雨")) {
            return R.drawable.biz_plugin_weather_xiaoyu;
        } else if (weather.equals("阴")) {
            return R.drawable.biz_plugin_weather_yin;
        } else if (weather.equals("雨夹雪")) {
            return R.drawable.biz_plugin_weather_yujiaxue;
        } else if (weather.equals("阵雪")) {
            return R.drawable.biz_plugin_weather_zhenxue;
        } else if (weather.equals("中雪")) {
            return R.drawable.biz_plugin_weather_zhongxue;
        } else {
            return R.drawable.biz_plugin_weather_duoyun;
        }
    }

    public interface LocationApiInterface {

        public void onSuccess(LocationBean beans);

        public void onFail();
    }

    public interface WeatherApiInterface {

        public void onSuccess(List<WeatherBean> beans);

        public void onFail();
    }
}
